package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.queryParams.HisPrQueryParams;
import com.css.fxfzypg.modules.baseData.repository.HisPrRepository;
import com.css.fxfzypg.modules.baseData.entity.HisPrEntity;
import com.css.fxfzypg.modules.baseData.service.HisprService;
import com.css.fxfzypg.modules.baseData.verify.HisPrExcelVerifyHandler;
import com.css.fxfzypg.modules.baseData.vo.HisPrExcelVo;
import com.css.fxfzypg.modules.baseData.vo.HisPrVO;
import com.css.fxfzypg.modules.baseData.vo.SysMenuVo;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.ReportManagement;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportManagementService;
import com.css.fxfzypg.modules.suggestinfo.analysis.suggestionanalysis.service.SuggestionAnalysisService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;

/**
 * @author y1fan
 * @create 2022-08-22 9:53
 */
@Service
public class HisprServiceImpl implements HisprService {

    @Resource
    SysRoleService sysRoleService;
    @Resource
    SUserService sUserService;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    private HisPrRepository hisPrRepository;
    @Resource
    HisPrExcelVerifyHandler hisPrExcelVerifyHandler;
    @Resource
    private PreAssessTaskService preAssessTaskService;
    @Resource
    private ReportManagementService reportManagementService;
    @Resource
    SetEarthquakeMapService setEarthquakeMapService;
    @Resource
    SuggestionAnalysisService suggestionAnalysisService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveHisPr(HisPrEntity hisPrEntity) throws UnsupportedEncodingException {
        hisPrEntity.setId(UUIDGenerator.getUUID());
        List<SysMenuVo> sysMenuList = getSAreaTree("1");//获取所有省
        BigDecimal dhpEpicenterLongitude = hisPrEntity.getDhpEpicenterLongitude();//经度
        BigDecimal dhpEpicenterLatitude = hisPrEntity.getDhpEpicenterLatitude();//纬度
        //根据经纬度获取省id
        String param = dhpEpicenterLongitude.toString()+" "+dhpEpicenterLatitude.toString();
        String provinceName = hisPrRepository.getProvinceName(param);
        if(PlatformObjectUtils.isNotEmpty(provinceName)){
            for(SysMenuVo sysMenuVo : sysMenuList) {
                String name = sysMenuVo.getName();
                if(provinceName.equals(name)){
                    hisPrEntity.setProvinceId(sysMenuVo.getValue());
                }
            }
        }
        hisPrEntity.setDelFlag(YNEnum.N.toString());
        String userID = PlatformSessionContext.getUserID();
        hisPrEntity.setDhpCreateUser(userID);
        hisPrEntity.setDhpCreateTime(PlatformDateUtils.getCurrentTimestamp());
        return hisPrRepository.saveHisPr(hisPrEntity);
    }

    @Override
    public Map<String, Object> getHisPrById(String id)  {
    //public Map<String, Object> getHisPrById(String id) {
        Map<String, Object> map = new HashMap<>();
        //历史预评估结果数据
        HisPrEntity hisPrEntity = hisPrRepository.getHisPrById(id);
        map.put("hisPr",hisPrEntity);
        if(PlatformObjectUtils.isNotEmpty(hisPrEntity.getDhpTaskNum())){
            //获取报告
            PreAssessTaskEntity preAssessTaskEntity = preAssessTaskService.getPreAssessTaskByTaskNum(hisPrEntity.getDhpTaskNum());//获取预评估任务
            map.put("task", preAssessTaskEntity);
            ReportManagement reportManagement = reportManagementService.getReport(preAssessTaskEntity.getReportId(), "4", "0");//根据报告id获取报告详情
            if(PlatformObjectUtils.isNotEmpty(reportManagement)) {
                //详本报告上传人id 获取姓名
                if (PlatformObjectUtils.isNotEmpty(reportManagement.getMinuteReportUploadUserId())) {
                    SUser sUser = CreateGson.createGson().fromJson(sUserService.getSUser(reportManagement.getMinuteReportUploadUserId()), SUser.class);
                    reportManagement.setMinuteReportUploadUserName(sUser.getUserName());
                }
                //简本报告上传人id 获取姓名
                if (PlatformObjectUtils.isNotEmpty(reportManagement.getSimpleReportUploadUserId())) {
                    SUser sUser = CreateGson.createGson().fromJson(sUserService.getSUser(reportManagement.getSimpleReportUploadUserId()), SUser.class);
                    reportManagement.setSimpleReportUploadUserName(sUser.getUserName());
                }
                map.put("report", reportManagement);
            }
            //建议分析
            List<PreAssessTaskEntity> preAssessTaskItem = preAssessTaskService.getSubTask(preAssessTaskEntity.getId());//获取当前任务下的子任务
            String lonlat = hisPrEntity.getDhpEpicenterLongitude()+" "+hisPrEntity.getDhpEpicenterLatitude();
            if(PlatformObjectUtils.isNotEmpty(preAssessTaskItem)){
                //根据经纬度判断该点在哪个子任务中
                for(PreAssessTaskEntity preAssessTask :preAssessTaskItem){
                    String taskId = preAssessTask.getId();
                    boolean taskRegionContainsLonLat = setEarthquakeMapService.isTaskRegionContainsLonLat(taskId, lonlat);
                    if(taskRegionContainsLonLat){
                        //根据子任务任务编号获取建议
                        Map<String, Object> maps = suggestionAnalysisService.getDataByTaskNum2(preAssessTask.getTaskNum());
                        map.putAll(maps);
                        break;
                    }
                }
            }else{
                Map<String, Object> dataByTaskNum = suggestionAnalysisService.getDataByTaskNum(preAssessTaskEntity.getTaskNum());
                map.putAll(dataByTaskNum);
                //根据父任务任务编号获取建议
                Map<String, Object> maps = suggestionAnalysisService.getDataByTaskNum2(preAssessTaskEntity.getTaskNum());
                map.putAll(maps);
            }
        }else{
            map.put("report","");
            map.put("suggest","");
            map.put("task", "");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHisPr(HisPrEntity hisPrEntity) {
        String userID = PlatformSessionContext.getUserID();
        hisPrEntity.setDhpUpdateUser(userID);
        hisPrEntity.setDhpUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        return hisPrRepository.updateHisPr(hisPrEntity);
    }

    @Override
    public Map<String,Object> getAllHisPrByParams(HisPrQueryParams queryParams) {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        StringBuilder roles = new StringBuilder();
        for(int i=0;i<maps.size();i++){
            Map map = maps.get(i);
            roles.append(map.get("roleCode")+",");
        }
        //当前登录人所有的角色
        String allRole = roles.toString();
        Map<String, Object> map = new HashMap<>();
        if(allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE) || allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)){
            map = hisPrRepository.getAllHisPrByParams(queryParams);
        } else if(allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)||allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)){
            SUser sUser = CreateGson.createGson().fromJson(sUserService.getSUser(userId), SUser.class);
            String provinceId = sUser.getProvinceId();
            map = hisPrRepository.getAllHisPrByParams(queryParams, provinceId);
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteHisPr(List<String> ids) {
        String userID = PlatformSessionContext.getUserID();
        Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
        return hisPrRepository.deleteHisPr(ids,currentTimestamp,userID);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportExcel1(HttpServletResponse response, List<String> ids)throws IOException {
        if (PlatformObjectUtils.isNotEmpty(ids)) {
            List<HisPrExcelVo> list  = new ArrayList<>();
            for (String id : ids) {
                HisPrExcelVo hisPrExcelVo = hisPrRepository.getHisPrVoById(id);
                list.add(hisPrExcelVo);
            }
            if (list == null || list.size() <= 0) {
                throw new RuntimeException("数据为空,无法导出！");
            }
            try {
                EasyPoiExcelUtil.exportExcel(list, null, "sheet", HisPrExcelVo.class, "历史预评估数据", response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportExcel2(HttpServletResponse response, HisPrQueryParams queryParams)throws IOException {
        List<HisPrExcelVo> noPageHisPrByParams = hisPrRepository.getNoPageHisPrByParams(queryParams);
        if (PlatformObjectUtils.isNotEmpty(noPageHisPrByParams)) {
            try {
                EasyPoiExcelUtil.exportExcel(noPageHisPrByParams, null, "sheet", HisPrExcelVo.class, "历史预评估数据", response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            throw new RuntimeException("数据为空,无法导出！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importExcel(MultipartFile file) throws IOException{
        ImportParams params = new ImportParams();
        params.setHeadRows(2);
        params.setNeedVerify(true);
        params.setVerifyHandler(hisPrExcelVerifyHandler);
        Map<String, Object> map = new HashMap<>();
        boolean res = false;
        try {
            Date date = new Date();
            String userId = PlatformSessionContext.getUserID();
            InputStream inputStream = file.getInputStream();
            //解析excel
            ExcelImportResult<HisPrEntity> result = ExcelImportUtil.importExcelMore(inputStream, HisPrEntity.class, params);
            List<HisPrEntity> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for(HisPrEntity hisPrEntity : failList){
                    errorMsg.append("<font size='4px' ><br>").append("第").append(hisPrEntity.getRowNum() + 1).append("行： ").append(hisPrEntity.getErrorMsg()).append("</font>");
                }
                map.put("res",res);
                map.put("mess",errorMsg);
                return map;
            }
            List<SysMenuVo> sysMenuList = getSAreaTree("1");//获取所有省
            List<HisPrEntity> resultData = result.getList();
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                List<HisPrEntity> list = new ArrayList<>();
                for(HisPrEntity hisPrEntity : resultData){
                    hisPrEntity.setId(UUIDGenerator.getUUID());
                    BigDecimal dhpEpicenterLongitude = hisPrEntity.getDhpEpicenterLongitude();//经度
                    BigDecimal dhpEpicenterLatitude = hisPrEntity.getDhpEpicenterLatitude();//纬度
                    //根据经纬度获取省id
                    String param = dhpEpicenterLongitude.toString()+" "+dhpEpicenterLatitude.toString();
                    String provinceName = hisPrRepository.getProvinceName(param);
                    if(PlatformObjectUtils.isNotEmpty(provinceName)){
                        for(SysMenuVo sysMenuVo : sysMenuList) {
                            String name = sysMenuVo.getName();
                            if(provinceName.equals(name)){
                                hisPrEntity.setProvinceId(sysMenuVo.getValue());
                            }
                        }
                    }
                    hisPrEntity.setDelFlag("0");
                    hisPrEntity.setDhpCreateUser(userId);
                    hisPrEntity.setDhpCreateTime(date);
                    list.add(hisPrEntity);
                }
                for(HisPrEntity entity : list){
                    res = hisPrRepository.saveHisPr(entity);
                    if(!res){
                        break;
                    }
                }
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("res",res);
        return map;
    }
    private List<SysMenuVo> getSAreaTree(String divisionId) throws UnsupportedEncodingException {
        String jsonStr = sysAreaService.jsonSAreaTree(URLEncoder.encode(divisionId, "UTF-8"));
        Gson gson = CreateGson.createGson();
        Type srItemsStandardType = new TypeToken<List<SysMenuVo>>() {
        }.getType();
        List<SysMenuVo> sysMenuList = gson.fromJson(jsonStr, srItemsStandardType);
        return sysMenuList;
    }




    @Override
    public boolean getRole() {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for(int i=0;i<maps.size();i++){
            Map map = maps.get(i);
            roles.append(map.get("roleCode")+",");
        }
        String allRole = roles.toString();
        if(allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)){
            return true;
        }
        return false;
    }

    @Override
    public List<HisPrEntity> getDataByLongitudeAndLatitude(String epiLon, String epiLat, BigDecimal o, String m) {
        return hisPrRepository.getDataByLongitudeAndLatitude( epiLon,  epiLat,  o,  m);
    }

    @Override
    public HisPrEntity getDateById(String hisPrId) {
        return hisPrRepository.getDateById(hisPrId);
    }

    @Override
    public Integer countByCounty(String name) {
        return hisPrRepository.countByCounty(name);
    }

    @Override
    public Integer countByCity(String name) {
        return hisPrRepository.countByCity(name);
    }

    @Override
    public Integer countByProvince(String name) {
        return hisPrRepository.countByProvince(name);
    }


}
